//
//  LYLogin.m
//  game
//
//  Created by naffan on 12-11-18.
//  Copyright (c) 2012年 naffan. All rights reserved.
//

#import "LYLogin.h"
#import "LeYou.h"

@implementation LYLogin
-(BOOL)isLogined
{
    lydb = [[LYDb alloc]init];
    [lydb create_back:@"create table if not exists userinfo (id integer primary key autoincrement,username text,uid integer,sid text,lastlogintime date,loginflag integer)"];
    db = [lydb open];
    userDefault = [NSUserDefaults standardUserDefaults];
    NSString* uid = [userDefault objectForKey:@"uid"];
    NSLog(@"[isLogined] SQL:SELECT * FROM `userinfo` WHERE `uid`='%@'",uid);
    rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM `userinfo` WHERE `uid`='%@'",uid]];
    NSLog(@"[isLogined] errormessage: %@",[db lastErrorMessage]);
    while ([rs next]){
         NSLog(@"[isLogined] username:%@ and loginflag :%@",[rs stringForColumn:@"username"],[rs stringForColumn:@"loginflag"]);
        if([[rs stringForColumn:@"loginflag"]intValue] == 1)
        {
            userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:[rs stringForColumn:@"uid"] forKey:@"uid"];
            NSLog(@"uid为%@的用户已经登入",[rs stringForColumn:@"uid"]);
            return YES;
        }
    }
    NSLog(@"用户没有登入");
    return NO;
}


//登陆
-(BOOL)logIn:(NSString*) username password:(NSString*) value
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    LeYou *leyou = [[LeYou alloc]init];
    NSString *url_base = LeYouApiUrlBase;
    NSString* url_api_for_login = [url_base stringByAppendingString:@"loginService.shtml"];
    NSURL *url = [NSURL URLWithString:url_api_for_login];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSString *name = username;
    NSString *password = [leyou md5:[value stringByAppendingFormat:PRIVATE_KEY]];
    NSString *mac = [leyou md5:[appid stringByAppendingFormat:@"%@%@%@%@",name,password,partner,PRIVATE_KEY]];
    NSLog(@"[logIn] 参数:appid :%@  username : %@ password :%@ partner :%@ sign : %@",appid,username,password,partner,[appid stringByAppendingFormat:@"%@%@%@%@",name,password,partner,PRIVATE_KEY]);
    
    [request setPostValue:appid forKey:@"appid"];
    [request setPostValue:name forKey:@"username"];
    [request setPostValue:password forKey:@"password"];
    [request setPostValue:partner forKey:@"partner"];
    [request setPostValue:mac forKey:@"mac"];
    [request startSynchronous];
    NSString *response = [request responseString];
    NSLog(@"[logIn] API返回:%@",response);
    NSDictionary *statuses = [parser objectWithString:response];
    NSString* uid = [[statuses objectForKey:@"info"]objectForKey:@"uid"];
    NSString* sid = [[statuses objectForKey:@"info"]objectForKey:@"sid"];
    [leyou release];
    [parser release];
    if([[statuses objectForKey:@"result" ]intValue] == 1)
    {
        NSLog(@"[logIn] UID:%@ 登入成功",uid);
        //存储信息
        userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setObject:uid forKey:@"uid"];
        [userDefault setObject:sid forKey:@"sid"];
        NSLog(@"[logIn] userDefault : %@" , [userDefault objectForKey:@"uid"]);
        //插入数据库
        lydb = [[LYDb alloc]init];
        db = [lydb open];
        rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM `userinfo` WHERE `uid`='%@'",uid]];
        NSString* SQL = nil;
        if(rs != nil){
            SQL =[NSString stringWithFormat:@"UPDATE `userinfo` SET `sid` = '%@',`loginflag` = '1', `lastlogintime` = '%@' WHERE `uid` ='%@'", sid,[NSDate dateWithTimeIntervalSinceNow: +(8*60*60)],uid];
        }else{
            SQL =[NSString stringWithFormat:@"INSERT INTO `userinfo` (`username`,`uid`,`sid`,`loginflag`) VALUES ('%@','%@','%@','%@')",username,[[statuses objectForKey:@"info"]objectForKey:@"uid"],[[statuses objectForKey:@"info"]objectForKey:@"sid"],@"1"];
        }
        NSLog(@"[logIn] SQL:%@",SQL);
        [db executeUpdate:SQL];
        NSLog(@"[logIn] errormessage: %@",[db lastErrorMessage]);
        return YES;
    }else{
        NSLog(@"[logIn] 登入失败");
        return NO;
    }
}

-(BOOL) logOut
{
    userDefault = [NSUserDefaults standardUserDefaults];
    NSLog(@"[logOut] userDefault : %@" , [userDefault objectForKey:@"uid"]);
    lydb = [[LYDb alloc]init];
    db = [lydb open];
    NSLog(@"[logOut] SQL : %@" , [NSString stringWithFormat:@"UPDATE `userinfo` SET `loginflag` = '0' WHERE `uid` ='%@'",[userDefault objectForKey:@"uid"]]);
    Boolean logout_res = [db executeUpdate:[NSString stringWithFormat:@"UPDATE `userinfo` SET `loginflag` = '0' WHERE `uid` ='%@'",[userDefault objectForKey:@"uid"]]];
    [lydb release];
    if(logout_res == YES){
        return YES;
    }else{
        return NO;
    }
}


//注册API
-(BOOL)registerUser:(NSString*) username password:(NSString*) value
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    LeYou *leyou = [[LeYou alloc]init];
    NSString *url_base = LeYouApiUrlBase;
    NSString* url_api_for_login = [url_base stringByAppendingString:@"regService.shtml"];
    NSURL *url = [NSURL URLWithString:url_api_for_login];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSString *name = username;
    NSString *password = [leyou md5:[value stringByAppendingFormat:PRIVATE_KEY]];
    NSString *mac = [leyou md5:[appid stringByAppendingFormat:@"%@%@%@%@",name,password,partner,PRIVATE_KEY]];
    NSLog(@"[registerUser] 参数:appid :%@  username : %@ password :%@ partner :%@ sign : %@",appid,username,password,partner,[appid stringByAppendingFormat:@"%@%@%@%@",name,password,partner,PRIVATE_KEY]);

    [request setPostValue:appid forKey:@"appid"];
    [request setPostValue:name forKey:@"username"];
    [request setPostValue:password forKey:@"password"];
    [request setPostValue:partner forKey:@"partner"];
    [request setPostValue:mac forKey:@"mac"];
    [request startSynchronous];
    NSString *response = [request responseString];
    NSLog(@"[registerUser] API返回:%@",response);
    NSDictionary *statuses = [parser objectWithString:response];
    [leyou release];
    [parser release];
    
    if([[statuses objectForKey:@"result" ]intValue] == 1)
    {
        NSLog(@"[registerUser] SQL:INSERT INTO `userinfo` (`username`,`uid`,`sid`,`loginflag`) VALUES ('%@','%@','%@','%@')",username,[[statuses objectForKey:@"info"]objectForKey:@"uid"],[[statuses objectForKey:@"info"]objectForKey:@"sid"],@"0");
        lydb = [[LYDb alloc]init];
        db = [lydb open];
        [db executeUpdate:[NSString stringWithFormat:@"INSERT INTO `userinfo` (`username`,`uid`,`sid`,`loginflag`) VALUES ('%@','%@','%@','%@')",username,[[statuses objectForKey:@"info"]objectForKey:@"uid"],[[statuses objectForKey:@"info"]objectForKey:@"sid"],@"0"]];
        NSLog(@"[registerUser] errormessage: %@",[db lastErrorMessage]);
        NSLog(@"UID:%@ 用户注册成功",[[statuses objectForKey:@"info"]objectForKey:@"uid"]);
        return YES;
    }else{
        NSLog(@"注册失败");
        return NO;
    }
}

//二次认证API
-(NSString*)twiceConfirm:(NSInteger*)uid sid:(NSInteger*) value
{
    //SBJSON *parser = [[SBJSON alloc] init];
    LeYou *leyou = [[LeYou alloc]init];
    NSString *url_base = LeYouApiUrlBase;
    NSString* url_api_for_login = [url_base stringByAppendingString:@"regService.shtml"];
    NSURL *url = [NSURL URLWithString:url_api_for_login];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSString *mac = [leyou md5:[appid stringByAppendingFormat:@"%d%d%@",uid,value,PRIVATE_KEY]];
    
    [request setPostValue:appid forKey:@"appid"];
    [request setPostValue:uid forKey:@"uid"];
    [request setPostValue:value forKey:@"sid"];
    [request setPostValue:mac forKey:@"mac"];
    [request startSynchronous];
    NSString *response = [request responseString];
    NSError *error = [request error];
    if (!error) {
        NSLog(@"%@",response);
        // NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[parser objectWithString:response error:nil]];
        // NSLog(@"%@",array);
    }else{
        response = nil;
    }
    
    [leyou release];
    return response;
}

//找回密码地址
-(id)findpassword
{
    LeYou *leyou = [[LeYou alloc]init];
    NSString *url_base = LeYouApiUrlBase;
    NSString* url_api_for_login = [url_base stringByAppendingString:@"getpassword.shtml"];
    NSURL *url = [NSURL URLWithString:url_api_for_login];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSString *mac = [leyou md5:[appid stringByAppendingString:PRIVATE_KEY]];
    [request setPostValue:appid forKey:@"appid"];
    [request setPostValue:mac forKey:@"mac"];
    [request startSynchronous];
    NSString *response = [request responseString];
    NSError *error = [request error];
    if (!error) {
         NSLog(@"%@",response);
         // NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[parser objectWithString:response error:nil]];
          // NSLog(@"%@",array);
     }else{
         response = nil;
     }
                     
     [leyou release];
     return response;

}


//找回密码地址
-(NSString*)getRegisterName
{
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    LeYou *leyou = [[LeYou alloc]init];
    NSString *url_base = LeYouApiUrlBase;
    NSString* url_api_for_login = [url_base stringByAppendingString:@"getusername.shtml"];
    NSURL *url = [NSURL URLWithString:url_api_for_login];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //NSString *mac = [leyou md5:[appid stringByAppendingString:PRIVATE_KEY]];
    //[request setPostValue:appid forKey:@"appid"];
    //[request setPostValue:mac forKey:@"mac"];
    [request startSynchronous];
    NSString *response = [request responseString];
    NSLog(@"[getRegisterName] API返回:%@",response);
    NSDictionary *statuses = [parser objectWithString:response];
    [leyou release];
    [parser release];
    return [statuses objectForKey:@"username" ];
    
}


@end
